/*
 * @lc app=leetcode.cn id=213 lang=javascript
 *
 * [213] 打家劫舍 II
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function (nums) {
  const size = nums.length;

  if (size === 1) return nums[0];
  if (size === 2) return Math.max(nums[0], nums[1]);

  const robRange = (nums, start, end) => {
    // 只有一间房子
    let first = nums[start];
    // 只有两间房子
    let second = Math.max(nums[start], nums[start + 1]);

    for (let i = start + 2; i <= end; i++) {
      let t = second;
      second = Math.max(nums[i] + first, second);
      first = t;
    }

    return second;
  };

  return Math.max(robRange(nums, 0, size - 2), robRange(nums, 1, size - 1));
};
// @lc code=end
